package xin.ryven.car.android.utils

import android.content.Context
import com.google.gson.Gson
import xin.ryven.car.android.data.PlaylistResponse
import xin.ryven.car.android.data.CoverResponse
import java.io.File

object LocalStorage {
    private const val PLAYLISTS_FILE = "playlists.json"
    private const val COVERS_FILE = "covers.json"
    private const val DISLIKED_FILE = "disliked.json"
    private val gson = Gson()

    fun savePlaylists(context: Context, response: PlaylistResponse) {
        val file = File(context.filesDir, PLAYLISTS_FILE)
        file.writeText(gson.toJson(response))
    }

    fun loadPlaylists(context: Context): PlaylistResponse? {
        val file = File(context.filesDir, PLAYLISTS_FILE)
        return if (file.exists()) {
            try {
                gson.fromJson(file.readText(), PlaylistResponse::class.java)
            } catch (e: Exception) {
                null
            }
        } else {
            null
        }
    }

    fun saveCovers(context: Context, response: CoverResponse) {
        val file = File(context.filesDir, COVERS_FILE)
        file.writeText(gson.toJson(response))
    }

    fun loadCovers(context: Context): CoverResponse? {
        val file = File(context.filesDir, COVERS_FILE)
        return if (file.exists()) {
            try {
                gson.fromJson(file.readText(), CoverResponse::class.java)
            } catch (e: Exception) {
                null
            }
        } else {
            null
        }
    }

    fun saveDislikedIds(context: Context, ids: List<Int>) {
        val file = File(context.filesDir, DISLIKED_FILE)
        file.writeText(gson.toJson(ids))
    }

    fun loadDislikedIds(context: Context): List<Int> {
        val file = File(context.filesDir, DISLIKED_FILE)
        return if (file.exists()) {
            try {
                val json = file.readText()
                gson.fromJson(json, Array<Int>::class.java)?.toList() ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
    }
}